# 导入Flask类
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
from gevent import pywsgi
import argparse,json
from flask_cors import CORS


# 实例化，可视为固定格式
app = Flask(__name__,template_folder='html')
CORS(app,resources=r'/*')
datas = {}
# route()方法用于设定路由；类似spring路由配置
#等价于在方法后写：app.add_url_rule('/', 'helloworld', hello_world)
@app.route('/hello')
def hello_world():
    return render_template('hello.html')
@app.route('/index')
def index():
    return render_template('index.html')

# 配置路由，当请求deal_request时交由deal_request()处理
# 默认处理get请求，我们通过methods参数指明也处理post请求
# 当然还可以直接指定methods = ['POST']只处理post请求, 这样下面就不需要if了
# http://192.168.10.2:10101/api/upload_data

@app.route('/api/getdata')
def get_data():
    global datas
    return jsonify({'code':200,'datas':datas})
@app.route('/api/upload_data', methods = ['GET', 'POST'])
def upload_request():
    global datas
    if request.method == "GET":
        # get通过request.args.get("param_name","")形式获取参数值
        get_q = request.args.get("data","")
        return jsonify({'code':200,'msg':'请用post方法'})
    elif request.method == "POST":
        # post通过request.form["param_name"]形式获取参数值
        datas = request.data.decode('utf-8')
        # print('收到数据包->',type(datas))
        datas = eval(datas)
        print(datas,type(datas))
        return jsonify({'code':200,'msg':'data commit success'})

if __name__ == '__main__':
    version='1.0.3'
    devdate='2023-7-18 21:34'
    args = argparse.ArgumentParser(description='dataServer v1.0')
    args.add_argument('-s',type=str,default='0.0.0.0',help='host address')
    args.add_argument('-p',type=int,default=10002,help='port')
    arg = args.parse_args()
    # 默认值：host=127.0.0.1, port=5000, debug=false
    # app.run(host="0.0.0.0",port=arg.p,debug=True)
    app.debug=True
    server = pywsgi.WSGIServer((arg.s,arg.p),app)
    print('----------------------------')
    print('  version:',version)
    print('  devdate:',devdate)
    print('----------------------------')
    print('server start runing....')
    print('cors runing...')
    print('host:',arg.s,' port:',arg.p)
    server.serve_forever()